package cn.itsource.exam.service.impl;

import cn.itsource.exam.domain.Login;
import cn.itsource.exam.domain.TeacherInfo;
import cn.itsource.exam.domain.StudentInfo;
import cn.itsource.exam.mapper.LoginMapper;
import cn.itsource.exam.service.LoginService;
import cn.itsource.exam.util.Md5Helper;
import com.alipay.api.domain.ItemOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    LoginMapper loginMapper;
    @Override
    public Login login(Map map) {
        return loginMapper.login(map);
    }

    @Override
    public void loginSave(Login login) {
        loginMapper.insert(login);
    }

    @Override
    public StudentInfo selectForStuden(Map map) {
        return loginMapper.selectForStuden(map);
    }

    @Override
    public TeacherInfo selectForTeacher(Map map) {
        return loginMapper.selectForTeacher(map);
    }

    /**
     * 重置密码
     * @param id
     * @param request
     * @return
     */
    @Override
    public String resetPwd(Long id, HttpServletRequest request) {
        Login user = loginMapper.selectById(id);
        if(user == null){
            return "用户不存在,请确认!";
        }
        user.setPassword(Md5Helper.MD5("123456"));
        int count = loginMapper.updateById(user);
        return count > 0 ? "" : "重置密码失败!";
    }

    /**
     * 根据名字获取用户
     * @param map
     * @return
     */
    @Override
    public Login selectUserInfoByName(Map<String,Object> map) {
        List<Login> list = loginMapper.selectByMap(map);
        if(list != null && list.size() > 0){
            return list.get(0);
        }
        return null;
    }

    @Override
    public String resetPwd(Long[] ids) {
        try {
            for (Long id:ids) {
                Login user = loginMapper.selectById(id);
                if(user == null){
                    return "用户不存在,请确认!";
                }
                user.setPassword(Md5Helper.MD5("123456"));
                loginMapper.updateById(user);
            }
        } catch (Exception e) {
            return  "重置密码失败!";
        }
        return "";
    }
}
